//格式化时间
function dateFtt(fmt, date) { //author: meizz
    var o = {
        "M+": date.getMonth() + 1,                 //月份
        "d+": date.getDate(),                    //日
        "h+": date.getHours(),                   //小时
        "m+": date.getMinutes(),                 //分
        "s+": date.getSeconds(),                 //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function formatSubscribeTime(cellValue, options, rowObject) {
    var dateStr = "";
    if (cellValue) {
        var crtTime = new Date(cellValue);
        dateStr = dateFtt("yyyy-MM-dd hh:mm:ss", crtTime);
    }
    return dateStr;
}

//加载字典
function dictJudge(value, options, row) {
    //sex为自定义字典项
    var statusObj = vm.options.sex;
    for (var i = 0; i < statusObj.length; i++) {
        if (statusObj[i].value == value) {
            return '<span>' + statusObj[i].text + '</span>';
        }
    }
}

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'ranking/illegalvehicle/list',
        datatype: "json",
        colModel: [
            {label: 'id', name: 'id', index: 'id', width: 50, key: true, hidden: true},
            {label: '序号', name: 'ranking', index: 'RANKING', width: 30},
            {label: '违法车辆', name: 'vehiclePlate', index: 'VEHICLE_PLATE', width: 80},
            {label: '所有者', name: 'vehicleOwner', index: 'VEHICLE_OWNER', width: 80},
            {label: '违法数量', name: 'illegalNumber', index: 'ILLEGAL_NUMBER', width: 80},
            {
                label: '采集时间', name: 'collectionTime', index: 'COLLECTION_TIME', width: 80,
                formatter: function (cellvalue) {
                    return dateFtt("yyyy-MM-dd", new Date(cellvalue))
                }
            },
            {
                label: '违法类型',
                name: 'illegalType',
                index: 'ILLEGAL_TYPE',
                width: 80,
                formatter: function (cellvalue, option, rowObject) {
                    if (cellvalue === '73390' || cellvalue === '10391&10392' ) {
                        return "违法停车";
                    }
                    if (cellvalue === '16250' || cellvalue === '16251') {
                        return "闯红灯";
                    }
                }
            },
            // { label: '数据添加时间', name: 'addTime', index: 'ADD_TIME', width: 80 }
        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList: [10, 30, 50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth: true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader: {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames: {
            page: "page",
            rows: "limit",
            order: "order"
        },
        gridComplete: function () {
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
        }
    });
});

//初始化日期组件-年月日
function datePlugin() {
    $('#collection_time').datepicker({
        language: 'zh-CN',//显示中文
        startView: 0, //选择器开始界面 0：天（默认 1：月2：年3：十年 4：世纪
        minViewMode: 0,//最小选择精度 0：天（最小默认）
        maxViewMode: 2, //最大选择精度 4：世纪（最大默认）
        format: 'yyyy-mm-dd',//显示格式
        minView: "day",//设置只显示到月份
        // initialDate: new Date(),
        autoclose: true,//选中自动关闭
        // todayBtn: true//显示今日按钮
        clearBtn: true, //清除按钮
        todayHighlight: true //今日高亮
    });
}

var vm = new Vue({
    el: '#rrapp',
    data: {
        q: {
            illegalType: ''
        },
        showList: true,
        title: null,
        illegalVehicle: {}
    },
    methods: {
        query: function () {

            vm.reload();
        },
        reset: function () {
            vm.q.illegalType = '';
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.illegalVehicle = {};

            datePlugin();
            //设置默认日期
            vm.illegalVehicle.collectionTime = dateFtt('yyyy-MM-dd', new Date());
        },
        update: function (event) {
            var id = getSelectedRow();
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            datePlugin();
            vm.getInfo(id)
        },
        saveOrUpdate: function (event) {
            var url = vm.illegalVehicle.id == null ? "ranking/illegalvehicle/save" : "ranking/illegalvehicle/update";
            console.log("after:" + JSON.stringify(vm.illegalVehicle.illegalType));
            vm.illegalVehicle.illegalType = encodeURIComponent(vm.illegalVehicle.illegalType);
            console.log("before:" + JSON.stringify(vm.illegalVehicle.illegalType));
            if (vm.illegalVehicle.vehiclePlate == undefined || vm.illegalVehicle.vehiclePlate == null || vm.illegalVehicle.vehiclePlate == "") {
                alert('请输入车牌号码');
                return false;
            }
            if (vm.illegalVehicle.vehicleOwner == undefined || vm.illegalVehicle.vehicleOwner == null || vm.illegalVehicle.vehicleOwner == "") {
                alert('请输入车辆所有人');
                return false;
            }
            if (vm.illegalVehicle.illegalNumber == undefined || vm.illegalVehicle.illegalNumber == null || vm.illegalVehicle.illegalNumber == "") {
                alert('请输入违法数量');
                return false;
            }
            if (vm.illegalVehicle.illegalType == 'undefined' || vm.illegalVehicle.illegalType == undefined || vm.illegalVehicle.illegalType == null || vm.illegalVehicle.illegalType == "") {
                alert('违法类型不可为空');
                return false;
            }
            if (vm.isNumber(vm.illegalVehicle.illegalNumber)){
                alert('违法数量必须为数字');
                return false;
            }
            console.log("illegalType:" + JSON.stringify(vm.illegalVehicle.illegalType));
            if (vm.illegalVehicle.ranking == undefined || vm.illegalVehicle.ranking == null || vm.illegalVehicle.ranking == "") {
                alert('请输入序号');
                return false;
            }
            vm.illegalVehicle.collectionTime = $("#collection_time").val();
            console.log(vm.illegalVehicle.illegalType);
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.illegalVehicle),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows();
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                $.ajax({
                    type: "POST",
                    url: baseURL + "ranking/illegalvehicle/delete",
                    contentType: "application/json",
                    data: JSON.stringify(ids),
                    success: function (r) {
                        if (r.code == 0) {
                            alert('操作成功', function (index) {
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        } else {
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        getInfo: function (id) {
            $.get(baseURL + "ranking/illegalvehicle/info/" + id, function (r) {
                vm.illegalVehicle = r.illegalVehicle;

                //日期格式化
                vm.illegalVehicle.collectionTime = dateFtt("yyyy-MM-dd", new Date(vm.illegalVehicle.collectionTime));
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'illegalType': vm.q.illegalType},
                page: page
            }).trigger("reloadGrid");
        },
        // 判断序号是否为数字
        isNumber: function (num) {
            var numReg = /[^\d]/;
            if (!numReg.test(num)) {
                return false;
            } else {
                return true;
            }
        },
    }
});